# -*- coding: utf-8 -*-
#--------------------------------------------------------------------------
# Copyright (c) 2009 Barry Schwartz
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
# 
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.

import os
import re
from pyfilemagic import magic_cookie

cookie = magic_cookie(magic_cookie.MAGIC_SYMLINK)
cookie.load_magic()

def file_type(file_name):

    if not isinstance(file_name, bytes):
        file_name = file_name.encode()
    magic = cookie.examine_file(file_name)

    if re.match(r'OpenType[ \t]', magic, re.IGNORECASE):
        t = 'opentype'
    elif re.match(r'TrueType[ \t]', magic, re.IGNORECASE):
        t = 'truetype'
    elif re.match(r'PostScript Type 1[ \t]', magic, re.IGNORECASE):
        t = 'type1'
    elif re.match(r'Spline Font Database', magic, re.IGNORECASE):
        t = 'fontforge'
    elif re.match(r'TeX font metric data', magic, re.IGNORECASE):
        t = 'tfm'

    elif re.match(r'JPEG 2000[ \t]', magic, re.IGNORECASE):
        t = 'jpeg2000'
    elif re.match(r'SVG[ \t]', magic, re.IGNORECASE):
        t = 'svg'
    elif re.match(r'PDF[ \t]', magic, re.IGNORECASE):
        t = 'pdf'
    elif re.match(r'ms-windows metafont', magic, re.IGNORECASE):
        t = 'wmf'
    elif re.match(r'PostScript[ \t]', magic, re.IGNORECASE):
        t = 'postscript'

    else:
        extension = os.path.splitext(file_name)[1].lower()
        lookup = { '.otf' : 'opentype',
                   '.pfa' : 'type1',
                   '.pfb' : 'type1',
                   '.cff' : 'type2',
                   '.ttf' : 'truetype',
                   '.ttc' : 'truetype',
                   '.tfm' : 'tfm',
                   '.ofm' : 'ofm',
                   '.afm' : 'afm',
                   '.enc' : 'encoding',
                   '.map' : 'fontmap',
                   '.sfd' : 'fontforge' }
        try:
            t = lookup[extension]
        except:
            t = 'unknown'

    return t
